#version 330 core

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
}; 

/* 平行光 */
// struct Light {
//     vec3 direction;
//     vec3 ambient;
//     vec3 diffuse;
//     vec3 specular;   
// };
/* 聚光灯 */
struct Light {
    // 位置
    vec3 position;  
    // 照射方向
    vec3 direction;
    // 圆锥张角的余弦值
    float cutOff;  
    float outerCutOff;  
    // 颜色
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
    // 光照衰减
    float constant;
    float linear;
    float quadratic;
};
// /* 点光源 */
// struct Light {
//     // 位置
//     vec3 position;  
//     // 颜色
//     vec3 ambient;
//     vec3 diffuse;
//     vec3 specular;
//     // 光照衰减
//     float constant;
//     float linear;
//     float quadratic;
// };

in vec3 worldNormal;
in vec3 worldPos;
in vec2 TexCoord;

out vec4 Frag_Color;

uniform vec3 lightColor;
// uniform vec3 objectColor;
// uniform vec3 lightPos;
uniform vec3 viewPos;
uniform Material material;
uniform Light light;

void main(){
    /* 点光源 */
    // vec3 lightDir = normalize(light.position - worldPos);
    // float distance    = length(light.position - worldPos);
    // float attenuation = 1.0 / (light.constant + light.linear * distance + 
    // light.quadratic * (distance * distance));
    /* 点光源 */
    /* 聚光灯 */
    vec3 lightDir = normalize(light.position - worldPos); // 从某个点指向光照方向
    float epsilon   = light.cutOff - light.outerCutOff; // 用作分母的总差值
    float theta = dot(lightDir, normalize(-light.direction));
    /* 聚光灯 */

    // 环境光
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoord));
    // 漫反射
    vec3 normal = normalize(worldNormal);
    /*平行光*/
    // vec3 lightDir = normalize(-light.direction);
    /*平行光*/
    float diff = max(dot(worldNormal, lightDir), 0);
    vec3 diffuse = diff * vec3(texture(material.diffuse, TexCoord)) * light.diffuse;
    // 镜面反射
    // float specularStrength = 0.5;
    vec3 viewDir = normalize(viewPos - worldPos);
    vec3 reflectLightDir = reflect(-lightDir, worldNormal);
    float spec = pow(max(dot(viewDir, reflectLightDir), 0.0), material.shininess);
    vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoord));
    vec3 result;
    /* 聚光灯 */
    float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);  // 限制0-1之间
    result = ambient + (diffuse + specular) * intensity;
    /* 聚光灯 */
    // Frag_Color = vec4(vec3(texture(material.specular, TexCoord)), 1.0f);
    // Frag_Color = vec4(worldNormal, 1.0f);
    Frag_Color = vec4(result, 1.0f);
}
